package SaveServlet.course;

import com.lyq.bean.Course;
import com.lyq.bean.Student;
import com.lyq.bean.service.C_Service;
import com.lyq.bean.service.E_Service;
import com.lyq.bean.service.RecommendationService;
import com.lyq.bean.service.S_Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/RecommendCourse_Servlet")
public class RecommendCourse_Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public RecommendCourse_Servlet() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String campus = request.getParameter("campus");
        
        if (id == null) {
            id = "";
        }
        
        if (campus == null) {
            campus = "";
        }
        
        if (id.equals("seekall")) {
            List<Course> list = new ArrayList<Course>();
            // 获取所有课程
            list = (new C_Service()).seekAll_C(list);
            
            // 根据校区筛选课程
            if (campus != null && !campus.isEmpty()) {
                list = this.filterByCampus(list, campus);
            }
            
            request.setAttribute("list", list);
            request.getRequestDispatcher("/jsp/course/s/RecommendCourse.jsp?campus=" + campus).forward(request, response);
        } else if (id.equals("elect")) {
            // 处理推荐选课页面的选课请求
            String cNo = request.getParameter("No");
            HttpSession session = request.getSession();
            String sNo = (String)session.getAttribute("UNAME");
            Student student = (Student)session.getAttribute("student");
            String message = "";
            campus = request.getParameter("campus");
            
            // 检查时间冲突
            if (hasTimeConflict(cNo, sNo)) {
                message = "选课失败，与已选课程时间冲突！";
            } else {
                message = (new E_Service()).elect_C(cNo, sNo, message);
                if (message != null && !message.equals("") && !message.equals("选课成功")) {
                    // message已经包含错误信息
                } else {
                    message = "选课成功！";
                }
            }
            
            // 直接返回消息文本，不转发到JSP页面
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write(message);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String interest = request.getParameter("interest");
        String career = request.getParameter("career");
        String courseType = request.getParameter("courseType");
        String creditLoad = request.getParameter("creditLoad");
        String campus = request.getParameter("campus");
        
        if (interest == null) {
            interest = "";
        }
        
        if (career == null) {
            career = "";
        }
        
        if (courseType == null) {
            courseType = "";
        }
        
        if (creditLoad == null) {
            creditLoad = "";
        }
        
        if (campus == null) {
            campus = "";
        }
        
        // 获取当前学生信息
        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student");
        
        // 如果session中没有学生信息，则尝试从数据库获取
        if (student == null) {
            String sNo = (String) session.getAttribute("UNAME");
            if (sNo != null && !sNo.isEmpty()) {
                List<Student> students = new S_Service().seek_S("学号", "精确查询", sNo, new ArrayList<>());
                if (!students.isEmpty()) {
                    student = students.get(0);
                    session.setAttribute("student", student);
                }
            }
        }
        
        // 获取所有课程
        List<Course> allCourses = new ArrayList<Course>();
        allCourses = (new C_Service()).seekAll_C(allCourses);
        
        // 根据校区筛选课程
        if (!campus.isEmpty()) {
            allCourses = this.filterByCampus(allCourses, campus);
        }
        
        // 使用新的推荐算法
        RecommendationService recommendationService = new RecommendationService();
        Map<String, String> preferences = new HashMap<>();
        preferences.put("interest", interest);
        preferences.put("career", career);
        preferences.put("courseType", courseType);
        preferences.put("creditLoad", creditLoad);
        
        List<Course> recommendedCourses = new ArrayList<>();
        Map<String, String> recommendationReasons = new HashMap<>();
        Map<String, Object> progressReport = new HashMap<>();
        
        // 只使用新的推荐算法
        if (student != null) {
            // 获取学生已选课程
            E_Service eService = new E_Service();
            List<Course> electedCourses = eService.seek_ElectC(student.getNo());
            
            recommendedCourses = recommendationService.recommendCourses(allCourses, student, preferences);
            
            // 为每门推荐课程生成个性化推荐理由
            for (Course course : recommendedCourses) {
                String reason = recommendationService.generateRecommendationReason(course, student, electedCourses);
                recommendationReasons.put(course.getNo(), reason);
            }
            
            // 生成学生的培养方案进度报告
            progressReport = recommendationService.generateProgressReport(student, electedCourses);
        } else {
            // 使用默认学生对象进行推荐
            Student defaultStudent = new Student();
            defaultStudent.setNo("default");
            defaultStudent.setDepartment("计算机科学");
            defaultStudent.setGpa(3.0);
            
            // 创建一些默认的已选课程用于演示
            List<Course> electedCourses = new ArrayList<>();
            
            recommendedCourses = recommendationService.recommendCourses(allCourses, defaultStudent, preferences);
            
            // 为每门推荐课程生成个性化推荐理由
            for (Course course : recommendedCourses) {
                String reason = recommendationService.generateRecommendationReason(course, defaultStudent, electedCourses);
                recommendationReasons.put(course.getNo(), reason);
            }
            
            // 生成默认的培养方案进度报告
            progressReport = recommendationService.generateProgressReport(defaultStudent, electedCourses);
        }
        
        request.setAttribute("recommendedCourses", recommendedCourses);
        request.setAttribute("recommendationReasons", recommendationReasons);
        request.setAttribute("progressReport", progressReport);
        request.setAttribute("interest", interest);
        request.setAttribute("career", career);
        request.setAttribute("courseType", courseType);
        request.setAttribute("creditLoad", creditLoad);
        
        request.getRequestDispatcher("/jsp/course/s/RecommendCourse.jsp?campus=" + campus).forward(request, response);
    }
    
    // 根据校区筛选课程
    private List<Course> filterByCampus(List<Course> courses, String campus) {
        List<Course> filteredCourses = new ArrayList<Course>();
        for (Course course : courses) {
            if (course.getCampus() != null && course.getCampus().equals(campus)) {
                filteredCourses.add(course);
            }
        }
        return filteredCourses;
    }
    
    // 处理推荐请求的公共方法
    private void handleRecommendationRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String campus = request.getParameter("campus");
        if (campus == null) campus = "";
        
        // 获取当前学生信息
        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student");
        
        // 获取所有课程
        List<Course> allCourses = new ArrayList<Course>();
        allCourses = (new C_Service()).seekAll_C(allCourses);
        
        // 根据校区筛选课程
        if (!campus.isEmpty()) {
            allCourses = this.filterByCampus(allCourses, campus);
        }
        
        // 使用默认偏好设置
        Map<String, String> preferences = new HashMap<>();
        preferences.put("interest", "");
        preferences.put("career", "");
        preferences.put("courseType", "");
        preferences.put("creditLoad", "");
        
        List<Course> recommendedCourses = new ArrayList<>();
        Map<String, String> recommendationReasons = new HashMap<>();
        Map<String, Object> progressReport = new HashMap<>();
        
        // 只使用新的推荐算法
        if (student != null) {
            // 获取学生已选课程
            E_Service eService = new E_Service();
            List<Course> electedCourses = eService.seek_ElectC(student.getNo());
            
            RecommendationService recommendationService = new RecommendationService();
            recommendedCourses = recommendationService.recommendCourses(allCourses, student, preferences);
            
            // 为每门推荐课程生成个性化推荐理由
            for (Course course : recommendedCourses) {
                String reason = recommendationService.generateRecommendationReason(course, student, electedCourses);
                recommendationReasons.put(course.getNo(), reason);
            }
            
            // 生成学生的培养方案进度报告
            progressReport = recommendationService.generateProgressReport(student, electedCourses);
        } else {
            // 使用默认学生对象进行推荐
            Student defaultStudent = new Student();
            defaultStudent.setNo("default");
            defaultStudent.setDepartment("计算机科学");
            defaultStudent.setGpa(3.0);
            
            // 创建一些默认的已选课程用于演示
            List<Course> electedCourses = new ArrayList<>();
            
            RecommendationService recommendationService = new RecommendationService();
            recommendedCourses = recommendationService.recommendCourses(allCourses, defaultStudent, preferences);
            
            // 为每门推荐课程生成个性化推荐理由
            for (Course course : recommendedCourses) {
                String reason = recommendationService.generateRecommendationReason(course, defaultStudent, electedCourses);
                recommendationReasons.put(course.getNo(), reason);
            }
            
            // 生成默认的培养方案进度报告
            progressReport = recommendationService.generateProgressReport(defaultStudent, electedCourses);
        }
        
        request.setAttribute("recommendedCourses", recommendedCourses);
        request.setAttribute("recommendationReasons", recommendationReasons);
        request.setAttribute("progressReport", progressReport);
        
        request.getRequestDispatcher("/jsp/course/s/RecommendCourse.jsp?campus=" + campus).forward(request, response);
    }
    
    // 检查时间冲突
    private boolean hasTimeConflict(String newCourseNo, String studentNo) {
        // 获取学生已选课程
        List<Course> electedCourses = (new E_Service()).seek_ElectC(studentNo);
        
        // 获取所有课程信息
        List<Course> allCourses = new ArrayList<>();
        allCourses = (new C_Service()).seekAll_C(allCourses);
        
        // 找到新选课程的时间
        String newCourseTime = "";
        for (Course course : allCourses) {
            if (course.getNo().equals(newCourseNo)) {
                newCourseTime = course.getTime();
                break;
            }
        }
        
        // 检查与已选课程的时间是否冲突
        for (Course electedCourse : electedCourses) {
            String electedCourseNo = electedCourse.getNo();
            // 跳过自身
            if (electedCourseNo.equals(newCourseNo)) {
                continue;
            }
            
            // 获取已选课程的时间
            for (Course course : allCourses) {
                if (course.getNo().equals(electedCourseNo)) {
                    String electedCourseTime = course.getTime();
                    // 简单的时间冲突检测（实际应用中需要更复杂的逻辑）
                    if (newCourseTime.equals(electedCourseTime)) {
                        return true; // 发现时间冲突
                    }
                    break;
                }
            }
        }
        
        return false; // 没有时间冲突
    }
}